<script setup>
import { ref, reactive, nextTick, onMounted, defineProps, watch } from "vue";
import { getTextById,deleteNoteById } from '@/utils/note';
import { useRouter } from "vue-router";
import addmessage from '@/hooks/message.js';
import headerTitle from '../components/base/header.vue'
import http from "../utils/api";
const router = useRouter();
let navShow = ref(window.innerWidth > 900)
//监听视口宽度变化
window.onresize = () => {
    navShow.value = window.innerWidth>900
}
const id = Number(router.currentRoute.value.params.id);//用于获取文本的id
let uid = ref(null);//md格式的文本
let text = ref('');//md格式的文本
//网络请求获取全部文本
async function getDetalis(id) {
    if (typeof id != 'number') {
        addmessage('参数类型错误', 0);
        return
    }
    let res = await getTextById(id);
    if (res.code == 0) {
        text.value = res.data.text;
        uid.value = res.data.uid;
        console.log(res.data);
        getTitle();
        return
    }
    addmessage('查询失败', 0)
}
//滚动到指定位置
function scrollTo(top) {
    preview.value.$el.scroll({
        top: top - 20,
        behavior: 'smooth'
    })
}

let timmer;//滚动监听的timmer
onMounted(() => {

    // 获取全文
    getDetalis(id)
    //对滚动监听，0.5秒监听一次
    if (navShow.value) {
        preview.value.$el.addEventListener('scroll', e => {
            if (timmer) return;
            timmer = setTimeout(() => {
                scrollHeight.value = e.target.scrollTop
                timmer = null;
            }, 500)
        })
    }
})
//锚点数组
const titles = reactive([]);
let preview = ref(null);//预览组件dom
let scrollHeight = ref(0);//预览组件滚动top值
// 解析文本为导航数据
const getTitle = () => {
    nextTick(() => {
        //获取所有的标题
        const anchors = preview.value.$el.querySelectorAll('h1,h2,h3');
        // 获取标题的数据
        Array.from(anchors).forEach(item => {
            const obj = {
                left: Number(item.nodeName.slice(1, 2)) - 1,//标题等级
                title: item.innerText,//标题内容
                top: item.offsetTop - 10,//标题所对应的位置
            }
            titles.push(obj);
        })
    });
};

//通过index和scroolTop判断用户是否浏览到本组件
function isSelected(index) {
    let top = scrollHeight.value + 50
    if (index == 0 && titles.length > 1 && top < titles[1].top) {
        return true;
    }
    const thisDom = titles[index];
    let nextDom = { ...titles[index + 1] };
    if (index == titles.length - 1) {
        nextDom.top = preview.value.$el.scrollHeight - 100;
    }
    if (thisDom.top < top && nextDom.top > top) {
        return true
    }
    return false;
}

// 收缩侧边栏
function changeAside() {
    navShow.value = !navShow.value
    console.log(navShow.value);
}

// 点击侧边栏外部收起
function clickOutside(event) {
    const current = document.querySelector('#navigation');
    if (current) {
        if (!current.contains(event.target)) {
            navShow.value = false
        }
    }
}

// 监听侧边栏的显示
watch(() => navShow.value, (newValue) => {
    nextTick(() => {
        if(window.innerWidth>900) return;
        if (newValue) {
           setTimeout(() => {
            window.addEventListener('click', clickOutside)
           }, 500); 
        } else {
            window.removeEventListener('click', clickOutside)
        }
    })
})

// 更新按钮
function updateNote(){
    sessionStorage.setItem('editText',text.value)
    router.push('/edit/'+id)
}

// 删除按钮
function deleteNote(){
    deleteNoteById(id).then(
        res=>{
            if(res.code==0){
                addmessage('删除成功')
                router.push('/home')
            }else{
                addmessage('删除失败',0)
            }
        }
    )
}
</script>

<template>
    <div class="previewBody">
        <!-- 左侧导航区域渲染 -->
        <transition name="fromLeftToLeft">
            <div class="navigation" v-if="navShow" id="navigation">
                <template v-for="(item, index) in titles" :key="index">
                    <div class="navItem" :style="{
                        marginLeft: item.left * 10 + 'px',
                    }" :class="[
    {
        selected: isSelected(index)
    },
    {
        mainTitle: item.left == 0
    }
]" @click.stop="scrollTo(item.top)">
                        {{ item.title }}
                    </div>
                </template>
            </div>
        </transition>

        <section class="right">
            <headerTitle @change-aside="changeAside" @update-note="updateNote" @delete-note="deleteNote" :uid="uid"></headerTitle>

            <!-- 显示部分 -->
            <v-md-preview :text="text" class="preview" id="preview" ref="preview"></v-md-preview>
        </section>


    </div>
</template>

<style scoped>
.previewBody {
    position: relative;
    display: flex;
    width: 100vw;
    overflow-x: hidden;
    background-color: #fff;
}

.right {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100vh;
}



@media screen and (min-width:900px) {
    .navigation {
        width: 20vw;
        height: 100vh;
        overflow-y: scroll;
    }
    .preview {
        position: relative;
        /* height: 95vh; */
        flex: 1;
        overflow-y: scroll;
        /* margin-right: .5em; */
    }
}

@media not screen and (min-width:900px) {
    .navigation {
        position: fixed;
        z-index: 20;
        background-color: #fff;
        width: 50vw;
        height: 100vh;
        overflow-y: scroll;
    }
    .preview {
        position: relative;
        /* height: 95vh; */
        width: 100vw;
        flex: 1;
        overflow-y: scroll;
        /* margin-right: .5em; */
    }
}



.mainTitle {
    font-size: large;
    font-weight: 800 !important;
}

.navItem {
    padding: .5em .2em;
    font-size: smaller;
    cursor: pointer;
    /* transition: all .3s; */
    padding: 1em .5em;
    font-weight: 500;
}

.navItem:hover {
    background-color: rgba(0, 0, 0, 0.1);
    color: inherit;
}



.selected {
    /* background-color: ; */
    color: var(--color-theme);
}
</style>